package com.nanbei.graph;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;

/**
 * @ClassDescription: 拓扑排序
 * @JdkVersion: 1.8
 * @Author: libs
 * @Created: 2024/7/1 17:49
 */
public class TopologicalSortDFS {
    public static void main(String[] args) {
        Vertex v1 = new Vertex("网页基础");
        Vertex v2 = new Vertex("Java基础");
        Vertex v3 = new Vertex("JavaWeb");
        Vertex v4 = new Vertex("Spring框架");
        Vertex v5 = new Vertex("微服务框架");
        Vertex v6 = new Vertex("数据库");
        Vertex v7 = new Vertex("实战项目");

        v1.setEdges(Arrays.asList(new Edge(v3))); // +1
        v2.setEdges(Arrays.asList(new Edge(v3))); // +1
        v3.setEdges(Arrays.asList(new Edge(v4)));
        v6.setEdges(Arrays.asList(new Edge(v4)));
        v4.setEdges(Arrays.asList(new Edge(v5)));
        v5.setEdges(Arrays.asList(new Edge(v7)));
        v7.setEdges(Arrays.asList());

        ArrayList<Vertex> vertices = new ArrayList<>(Arrays.asList(v1, v2, v3, v4, v5, v6, v7));

        LinkedList<String> vertexLinkedList = new LinkedList<>();

        for (Vertex vertex : vertices) {
            dfs(vertex, vertexLinkedList);
        }
        System.out.println(vertexLinkedList);


    }

    private static void dfs(Vertex vertex, LinkedList<String> vertexLinkedList) {
        // 已经被访问过直接返回
        if (vertex.getStatus() == 2) {
            return;
        }
        // 当前节点正在访问中证明有环存在
        if (vertex.getStatus() == 1) {
            throw new RuntimeException("当前拓扑图中存在环！");
        }
        vertex.setStatus(1);
        List<Edge> edges = vertex.getEdges();
        for (Edge edge : edges) {
            Vertex linked = edge.getLinked();
            dfs(linked, vertexLinkedList);
        }
        vertex.setStatus(2);
        vertexLinkedList.push(vertex.getName());
    }
}
